package com.ocom.oauth.auth.replace;

import com.ocom.oauth.auth.CustomAbstractTokenGranter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 *
 *  说明：
 *    验证码
 *    定义验证码具体逻辑
 */
public class ReplaceTokenGranter extends CustomAbstractTokenGranter {

    private static final String REPLACE_TOKEN = "replace_token";

    private ReplaceTokenDetailService replaceTokenDetailService;

    public ReplaceTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, ReplaceTokenDetailService aiotUserDetailService) {
        super(tokenServices, clientDetailsService, requestFactory, REPLACE_TOKEN);
        this.replaceTokenDetailService  = aiotUserDetailService;
    }

    @Override
    protected UserDetails getUserDetails(Map<String, String> parameters) {
        String token = parameters.get("token");
        Long comId = Long.valueOf(parameters.get("comId"));

        if (token==null) {
            throw new InvalidGrantException("token传参错误或者为空值，请输入正确的token信息");
        }
        if (comId==null) {
            throw new InvalidGrantException("comId传参错误或者为空值，请输入正确的单位信息");
        }

        return replaceTokenDetailService.load(token,comId);
    }
}
